import routeList from '@/routes/modules'
import { defineStore } from 'pinia'

export const useMainStore = defineStore('main', {
  state: () => ({
    loading: true,
    version: '0.0.0',
    menus: {} as { [key: string]: Setting.Menu },
    settings: {
      title: ''
    }
  }),
  getters: {
    currentModule (state) {
      return state.settings.title
    }
  },
  actions: {
    updateLoading () {
      this.loading = false
    },
    updateMenu (data: { [key: string]: Setting.Menu }) {
      this.menus = data
    },
    updateVersion (version: string) {
      this.version = version
    },
    updateSettings (data: Setting.Config) {
      this.settings = data
    },
    async initMenu () {
      this.updateVersion('1.0.0')

      const menus: { [key: string]: Setting.Menu } = {}
      const getChilds = (routes: RouteConfig[]) => {
        routes.forEach((r: RouteConfig) => {
          const text = `${r.meta?.title}`
          if (!r.isAside) {
            return
          }

          menus[r.path] = {
            title: text,
            auth: r.auth,
            icon: `${r.meta?.icon}`,
            routes: []
          }

          if (menus[r.path]) {
            if (r.children && r.children.length) {
              r.children.forEach((sub: RouteConfig) => {
                if (sub.path.length === 0) {
                  return
                }
                let pat = ''
                let auth = ''
                if (sub.path.substr(0, 1) === '/') {
                  pat = sub.path
                } else {
                  pat = `${r.path}/${sub.path}`
                }
                if (sub.auth) {
                  auth = sub.auth
                } else {
                  auth = `${r.auth}`
                }
                return menus[r.path].routes?.push({
                  module: r.path,
                  auth: auth,
                  title: `${sub.meta?.title}`,
                  path: pat,
                  icon: `${sub.meta?.icon}`,
                  hidden: sub.hidden,
                  active: sub.active
                })
              })
            }
          }
        })
      }
      getChilds(routeList)

      this.updateMenu(menus)

      this.updateLoading()
    }
  }
})
